package com.lanou.web.controller;

import com.alibaba.fastjson.JSON;
import com.lanou.entity.Commodity;
import com.lanou.entity.CookieUtils;
import com.lanou.entity.TbUser;
import com.lanou.service.CartPageService;
import com.lanou.utils.HttpClientUtils;
import com.lanou.utils.ShiHuiResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
public class CartPageController {
    @Autowired
    private CartPageService cartPageService;

    @Value("${GET_USER_COOKIE_URL}")
    private String GET_USER_COOKIE_URL;
    @Value("${MAX_TiME}")
    private Integer MAX_TiME;


    @ApiOperation("添加购物车")
    @ResponseBody
    @RequestMapping("/cart/add")
    public Map<String, Object> addCartList(Long itemId, Integer num,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        String token = CookieUtils.getCookieValue(request, "token");

        // 已登录用户
        if (token != null) {
            TbUser user = HttpClientUtils.getObject(GET_USER_COOKIE_URL + token, TbUser.class);
            cartPageService.addCart(itemId, num, user.getId());
            return ShiHuiResult.ok();
        } else {// 未登录用户
            String cart = CookieUtils.getCookieValue(request, "cart", true);
            if (cart == null) {
                cart = "[]";
            }
            cart = cartPageService.updateCart(cart, itemId, num);

            CookieUtils.setCookie(request, response, "cart", cart, MAX_TiME, true);

            return ShiHuiResult.ok();
        }
    }


    @ApiOperation("加载购物车")
    @GetMapping("/cart")
    public String showCartList(HttpServletRequest request, Model model) {
        String token = CookieUtils.getCookieValue(request, "token");

        List<Commodity> catItemList;
        // 已登录用户
        if (token != null) {
            TbUser user = HttpClientUtils.getObject(GET_USER_COOKIE_URL + token, TbUser.class);
            catItemList = cartPageService.listCartItems(user.getId());
        } else {// 未登录用户
            String cart = CookieUtils.getCookieValue(request, "cart", true);
            if (cart == null) {
                cart = "[]";
            }
            catItemList = JSON.parseArray(cart, Commodity.class);
        }

        for (Commodity commodity : catItemList) {
            System.out.println(commodity);
        }

        model.addAttribute("cartList", catItemList);
        return "cart";
    }
}
